﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CommunityServer.WebServices.MediaGalleries;
using System.Web;
using System.Threading;

namespace nb.development.csmediamanager
{
    public partial class TagBox : Form
    {
        public TagBox(List<MediaGalleryPost> posts, Guid SiteId)
        {
            InitializeComponent();
            this.posts = posts;
            this.SiteId = SiteId;
        }

        private List<MediaGalleryPost> posts;
        private Guid SiteId;

        private void btnOk_Click(object sender, EventArgs e)
        {
            progress.Show();
            Cursor = Cursors.WaitCursor;
            btnOk.Hide();
            btnCancel.Hide();
            tags.Hide();
            Height = 73;
            progress.Maximum = posts.Count;
            progress.Value = 0;
            foreach (MediaGalleryPost post in posts)
                foreach (string s in tags.Text.Split(new char[] { ',' }))
                    if (!post.Keywords.Contains(HttpUtility.HtmlEncode(s.Trim())))
                        post.Keywords.Add(HttpUtility.HtmlEncode(s.Trim()));
            Updater u = new Updater(posts, SiteId);
            u.UpdatedPost += new UploadedPost(u_UpdatedPost);
            u.UpdateCompleded += new UploadCompleted(u_UpdateCompleded);
            Thread t = new Thread(new ThreadStart(u.Update));
            t.Start();
        }

        void u_UpdateCompleded()
        {
            if (progress.InvokeRequired)
            {
                UploadCompleted done = new UploadCompleted(u_UpdateCompleded);
                try { progress.Invoke(done); }
                catch { }
            }
            else
            {
                progress.Value = posts.Count;
                Thread.Sleep(1000);
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        void u_UpdatedPost(int index, int count)
        {
            if (progress.InvokeRequired)
            {
                UploadedPost done = new UploadedPost(u_UpdatedPost);
                try { progress.Invoke(done, index, count); }
                catch { }
            }
            else progress.Value = index;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
    }
}
